﻿using B.S.Base.Read.API.Application.Command;
using B.S.Base.Read.API.Dto;
using B.S.BaseData.Common;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using WEBAPI.API.Application.Command;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Read.API.Application.CommandHandLer
{
    public class LoginCommandHandLer : IRequestHandler<LoginCommand, APIResult<LoginResultDto>>
    {
        private readonly JwtTools _jwtTools;
        private readonly IConfiguration _configuration;
        private readonly IBaseRepostiy<AccountModel> _repostiy;
        private readonly IBaseRepostiy<UserRoleModel> userrole;
        private readonly IBaseRepostiy<DeptModel> _deptModel;
        private readonly IBaseRepostiy<RoleModel> _roleModel;
        public LoginCommandHandLer(IBaseRepostiy<AccountModel> repostiy, IBaseRepostiy<UserRoleModel> userrole, IBaseRepostiy<DeptModel> deptModel, IBaseRepostiy<RoleModel> roleModel, JwtTools jwtTools, IConfiguration configuration)
        {
            this._repostiy = repostiy;
            this.userrole = userrole;
            this._deptModel = deptModel;
            this._roleModel = roleModel;
            _jwtTools = jwtTools;
            _configuration = configuration;
        }

        public Task<APIResult<LoginResultDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<LoginResultDto> result = new APIResult<LoginResultDto>();

            var user = _repostiy.GetAll().FirstOrDefault(x => x.AccountName == request.AccountName && x.Pwd == request.Pwd);
            if (user != null)
            {
                List<int> rids = userrole.GetAll().Where(x => x.AccountId == user.AccountId).Select(x => x.RoleId).ToList();
                List<string> roleNames = _roleModel.GetAll().Where(r => rids.Contains(r.RoleId)).Select(r => r.RoleName).ToList();
                var dept = _deptModel.GetAll().FirstOrDefault(x => x.DeptId == user.DeptId);
                var token = _jwtTools.JwtNewString(_configuration, user.AccountName, user.AccountId.ToString());

                result.Code = ResultCode.Ok;
                result.Message = "登录成功";
                result.Data = new LoginResultDto
                {
                    Account = user,
                    RoleIds = rids,
                    RoleNames = roleNames,
                    Dept = dept,
                    Token = token
                };
            }
            else
            {
                result.Code = ResultCode.Fail;
                result.Message = "账号和密码错误";
            }

            return Task.FromResult(result);
        }

    }
}
